//
//  TransitionMeun.swift
//  Swift30Days
//
//  Created by licheng ke on 2017/3/10.
//  Copyright © 2017年 licheng ke. All rights reserved.
//

import UIKit

class TransitionMeun:
        NSObject,
        UIViewControllerTransitioningDelegate,
        UIViewControllerAnimatedTransitioning
{
    var isPresenting = true;
    
    func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
     
        let container = transitionContext.containerView;
        let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)
        let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)
        
        let cpView = fromView?.snapshotView(afterScreenUpdates: false);
        
        let handleController = transitionContext.viewController(forKey: isPresenting ? UITransitionContextViewControllerKey.to : UITransitionContextViewControllerKey.from) as! Controller17_2;

        if isPresenting {
            container.addSubview(cpView!);
            container.addSubview(toView!);
            self.makerOffsetTransform(presented: handleController);
        }
        
        UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.8, options: .curveLinear, animations: { 
            if self.isPresenting {
                self.makerIndetifyTransform(presented: handleController);
            }
            else {
                self.makerOffsetTransform(presented: handleController);
                fromView?.transform = CGAffineTransform(translationX: 0, y: -SCREEN_H);
            }
        }) { (flag) in
            transitionContext.completeTransition(!transitionContext.transitionWasCancelled);
        }
        
    }
    
    func makerIndetifyTransform(presented:Controller17_2){
        presented.topLabel.transform = CGAffineTransform.identity
        presented.centerLabel.transform = CGAffineTransform.identity
        presented.missAction!.transform = CGAffineTransform.identity
    }
    
    func makerOffsetTransform(presented:Controller17_2){
        presented.topLabel.transform = CGAffineTransform(translationX: 0, y: -200);
        presented.centerLabel.transform = CGAffineTransform(translationX: -250, y: 0);
        presented.missAction!.transform = CGAffineTransform(translationX: 0, y: 2200);
    }
    
    
    func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
        return 0.5;
    }
    
    func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        self.isPresenting = true;
        return self;
    }
    
    func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        self.isPresenting = false;
        return self;
    }
}
